function [docs, doct] = root_Documents(hfile, type)
% ROOT::Documents  - get list of "Documents" (VB-Style interface)
%
% FORMAT:       [docs, doct] = BVQXfile.Documents([type]);
%
% Input fields:
%
%       type        if given, must be one of the valid 3/4 char types
%                   or a regexpi list of types '(ext1|ext2|ext3)'
%
% Output fields:
%
%       docs        currently loaded documents
%       doct        file types of loaded documents

% Version:  v0.7g
% Build:    9101521
% Date:     Oct-15 2009, 9:20 PM CEST
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 1 || ...
    numel(hfile) ~= 1 || ...
   ~isBVQXfile(hfile, 'root') || ...
    hfile.L ~= 1
    error( ...
        'BVQXfile:BadArgument', ...
        'Invalid call to ''%s''.', ...
        mfilename ...
    );
end
if nargin < 2 || ...
   ~ischar(type)
    type = '';
else
    type = lower(type(:)');
end

% get available objects (without ROOT!)
o = BVQXfile(0, 'objects');
o(1) = [];

% empty?
if isempty(o)
    docs = cell(0, 1);
    return;
end

% compile filename list
docs = {o(:).F};
docs = docs(:);
if nargout > 1 || ...
   ~isempty(type)
    doct = {o(:).S};
    doct = cat(1, doct{:});
    doct = {doct(:).Extensions};
    for dc = 1:numel(doct)
        doct{dc} = doct{dc}(1);
    end
    doct = cat(1, doct{:});
end

% replace missing filenames with numbers
for dc = 1:numel(docs)
    if isempty(docs{dc}) || ...
        any(strcmp(docs{dc}, docs(1:dc-1)))
        docs{dc} = dc;
    end
end

% only those of given type
if ~isempty(type)
    
    % only return those where initial index matches
    if any((3:4) == numel(type))
        
        % either as a simple match
        match = strcmpi(doct, type);
        
    % or
    else
        
        % as a regexpi match for multiple types
        match = (~isemptycell(regexpi(doct, type)));
    end
    
    % get matches
    docs = docs(match);
    
    % and also for type
    if nargout > 1
        doct = doct(match);
    end
end
